import util from '../utils/request'
import * as qiniu from 'qiniu-js'
const fetch = util.ajax

// 文件上传到后台
export function uploadFile(data) {
  return fetch({
    url: '/res/file/uploadImg',
    method: 'post',
    data: data,
    config: {
      headers: { 'Content-Type': 'multipart/form-data' }
    }
  })
}

//文件上传到七牛
export function uploadFileTo7n(data, calback) {
  getUploadToken().then(res => {
    let token = res.token
    qiniuFileUploader(token, data, calback)
  })
}

//获取七牛云token
function getUploadToken() {
  return fetch({
    url: '/blog/file/getUploadToken',
    method: 'get'
  })
}

function qiniuFileUploader(token, data, calback) {
  var file = data
  var fileName = new Date().getTime()
  let config = {
    useCdnDomain: true,
    region: qiniu.region.z0
  }
  let putExtra = {
    fname: file,
    params: {},
    mimeType: []
  }

  var observable = qiniu.upload(file, fileName, token, putExtra, config)
  window.console.log(observable)
  let observe = {
    next(res) {
      console.log('已上传大小，单位为字节：' + res.total.loaded)
      console.log('本次上传的总量控制信息，单位为字节：' + res.total.size)
      console.log('当前上传进度，范围：0～100：' + res.total.percent)
    },
    error(err) {
      console.log(err.code)
      console.log(err.message)
      console.log(err.isRequestError)
      console.log(err.reqId)
    },
    complete(res) {
      //完成后的操作
      //上传成功以后会返回key 和 hash  key就是文件名了！
      console.log(res)
      calback('http://resource.teemor.xyz/' + res.key)
    }
  }
  let subscription = observable.subscribe(observe)
}
